import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import Table from '@kuiper-components/page-table';

import { percent, number } from '../../../common/formatter';
import Progress from '../Progress';
import s from './BarTable.module.css';

export default function BarTable({ className, nameColName, barColName, data }) {
	const columns = React.useMemo(() => {
		const total = data.reduce((t, { value }) => t + value, 0);
		return [
			{
				key: 'name',
				title: nameColName,
				dataIndex: 'name',
				className: s.name,
			},
			{
				key: 'progress',
				title: barColName,
				dataIndex: 'value',
				className: s.progress,
				render(value, { color }) {
					return (
						<Progress percent={percent(value / total)} fillColor={color} />
					);
				},
			},
			{
				key: 'count',
				title: '',
				dataIndex: 'value',
				className: s.count,
				render: x => number(x),
			},
		];
	}, [data]);

	return (
		<Table
			className={cn(className, s.barTable)}
			type="local"
			rowKey="name"
			stateStoreType="state"
			columns={columns}
			data={data}
			total={data?.length || 0}
		/>
	);
}

BarTable.propTypes = {
	className: PropTypes.string,
	nameColName: PropTypes.string,
	barColName: PropTypes.string,
	data: PropTypes.arrayOf(
		PropTypes.shape({
			name: PropTypes.string.isRequired,
			value: PropTypes.string.isRequired,
			color: PropTypes.string,
		})
	),
};

BarTable.defaultProps = {
	className: s.barTable,
	columns: [],
	data: [],
};
